package com.share.homestay.web;

import com.share.homestay.entity.OrderLogs;
import com.share.homestay.entity.SysUser;
import com.share.homestay.exception.BusinessException;
import com.share.homestay.pojo.JsonResult;
import com.share.homestay.pojo.LoginUser;
import com.share.homestay.service.SysUserServiceFeign;
import com.share.homestay.utils.JwtUtils;
import com.share.homestay.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = "用户登录模块")
@RestController
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserServiceFeign sysUserServiceFeign;

    @ApiOperation(value = "用户登录接口", httpMethod = "POST", notes = "用户登录接口")
    @RequestMapping(value = "login")
    public JsonResult login(@RequestBody SysUser sysUser) {


        // 1 获取AuthenticationManager 对象 然后调用 authenticate() 方法
        // UsernamePasswordAuthenticationToken 实现了Authentication 接口
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(), sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //2 认证没通过 提示认证失败
        if (Objects.isNull(authenticate)) {
            throw new BusinessException("认证失败用户信息不存在");
        }

        //认证通过 使用userid 生成jwt token令牌
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获得当前用户的用户id
        String userId = loginUser.getSysUser().getUserId().toString();
        String token = JwtUtils.createJwt(userId);

        // 把用户信息存入到redis中
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("user",loginUser);
        //将当前用户信息存入redis
        redisUtil.set("login:"+userId, loginUser);

        //新增日志信息
        OrderLogs orderLogs = new OrderLogs(null,loginUser.getSysUser().getUserName(),"登录","登录",new Date(),null,null);
        sysUserServiceFeign.addOrderLogs(orderLogs);
        return JsonResult.success(params);
    }
}
